<template>
  <el-card class="task-center-container">
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
              v-model="searchForm.name"
              clearable
              placeholder="输入任务名称"
              @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon>
                <Search/>
              </el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.type" clearable placeholder="任务类型">
            <el-option :value="1" label="代购"/>
            <el-option :value="2" label="代取快递"/>
            <el-option :value="3" label="代办事务"/>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-input v-model="searchForm.campus" placeholder="校区"></el-input>
        </el-col>
        <el-col :span="6">
          <el-button :loading="loading" type="primary" @click="handleSearch">
            <el-icon>
              <Search/>
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh/>
            </el-icon>
            重置
          </el-button>
          <el-button type="success" @click="publishDialogVisible = true">
            <el-icon>
              <Plus/>
            </el-icon>
            发布任务
          </el-button>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 15px">
        <el-col :span="6">
          <div>金额范围：</div>
          <el-slider
              v-model="searchForm.rewardRange"
              :format-tooltip="(val) => `¥${val}`"
              :max="200"
              :step="5"
              range
              show-stops
          />
        </el-col>
        <el-col :span="6">
          <div>距离范围：</div>
          <el-slider
              v-model="searchForm.distanceRange"
              :format-tooltip="(val) => `${val}km`"
              :max="20"
              :step="1"
              range
              show-stops
          />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.sortBy" placeholder="排序方式">
            <el-option label="发布时间" value="createTime"/>
            <el-option label="报酬金额" value="reward"/>
            <el-option label="距离远近" value="distance"/>
            <el-option label="截止时间" value="deadline"/>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.sortOrder" placeholder="排序顺序">
            <el-option label="降序" value="desc"/>
            <el-option label="升序" value="asc"/>
          </el-select>
        </el-col>
      </el-row>
    </el-card>

    <div style="margin-top: 20px">
      <el-row v-loading="loading" :gutter="20">
        <el-col v-for="task in taskList" :key="task.id" :span="8">
          <TaskCard :task="task"/>
        </el-col>
      </el-row>

      <el-empty v-if="!loading && taskList.length === 0" description="暂无任务数据"/>
    </div>

    <el-row justify="center" style="margin-top: 30px">
      <el-pagination
          v-model:current-page="pageInfo.current"
          v-model:page-size="pageInfo.size"
          :page-sizes="[10, 20, 30, 50]"
          :total="pageInfo.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-row>
    <TaskDetailDialog
        v-model="detailDialogVisible"
        :task-id="selectedTaskId"
        @accept-task="handleAcceptTask"
    />
    <PublishTaskDialog
        v-model="publishDialogVisible"
        @published="handleTaskPublished"
    />
  </el-card>
</template>

<script setup>
import {onMounted, provide, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus, Refresh, Search} from '@element-plus/icons-vue'
import request from '@/utils/request'
import TaskDetailDialog from '@/components/TaskDetailDialog.vue'
import PublishTaskDialog from '@/components/PublishTaskDialog.vue'
import TaskCard from '@/components/TaskCard.vue'
import {confirm} from "@/utils/utils.js";

// 响应式数据
const loading = ref(false)
const taskList = ref([])
const detailDialogVisible = ref(false)
const publishDialogVisible = ref(false)
const selectedTaskId = ref(null)

// 搜索表单等其他逻辑... (保持不变)
const searchForm = reactive({
  name: '',
  type: null,
  campus: '',
  rewardRange: [0, 200],
  distanceRange: [0, 20],
  sortBy: 'createTime',
  sortOrder: 'desc'
})
const pageInfo = reactive({current: 1, size: 10, total: 0})

// 获取任务列表
const handleGetTaskList = async () => {
  loading.value = true
  const param = {status: 1}
  if (searchForm.name) param.name = searchForm.name
  if (searchForm.type) param.type = searchForm.type
  if (searchForm.campus) param.campus = searchForm.campus
  param.minReward = searchForm.rewardRange[0]
  param.maxReward = searchForm.rewardRange[1]
  param.minDistance = searchForm.distanceRange[0]
  param.maxDistance = searchForm.distanceRange[1]
  param.publishedByMe = false
  const orders = [{column: searchForm.sortBy, asc: searchForm.sortOrder === 'asc'}]
  const requestData = {page: pageInfo.current, size: pageInfo.size, param, orders}
  const data = await request.post('/task/page', requestData)
  taskList.value = data.records
  pageInfo.total = data.total
  loading.value = false
}

const handleSearch = () => {
  pageInfo.current = 1;
  handleGetTaskList()
}
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: null,
    campus: '',
    rewardRange: [0, 200],
    distanceRange: [0, 20],
    sortBy: 'createTime',
    sortOrder: 'desc'
  });
  pageInfo.current = 1;
  handleGetTaskList()
}
const handleSizeChange = (size) => {
  pageInfo.size = size;
  pageInfo.current = 1;
  handleGetTaskList()
}
const handleCurrentChange = (current) => {
  pageInfo.current = current;
  handleGetTaskList()
}

// 查看详情
const openDetailDialog = (task) => {
  selectedTaskId.value = task.id
  detailDialogVisible.value = true
}

// 接单
const handleAcceptTask = async (task) => {
  confirm('是否确认接单', async () => {
    await request.post('/task/accept/' + task.id)
    ElMessage.success('接单成功')
    await handleGetTaskList()
  })
}

// 任务发布成功
const handleTaskPublished = () => {
  ElMessage.success('任务发布成功')
  handleGetTaskList()
}

// 子组件接单后需要调用这个来刷新
provide('openDetailDialog', openDetailDialog)
provide('refreshTaskList', handleGetTaskList)

// 初始化
onMounted(() => {
  handleGetTaskList()
})
</script>

<style scoped>
.task-center-container {
  padding: 20px;
}

.search-card {
  border-radius: 8px;
}
</style>